package com.eboss2.sbs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.MyExpandableListViewAdapter;
import com.eboss2.sbs.adapter.ServiceExmineManagerAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.interfaces.ExmineCallbackListener;
import com.eboss2.sbs.model.CategoryListInfo;
import com.eboss2.sbs.model.ExmineManageInfo;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.dialog.pop.CommonPopupWindow;
import com.mytools.tool.views.MyListView;
import com.mytools.tool.views.SegmentView;
import com.tool.utils.utils.StringUtils;
import com.views.apptwolistview.model.FirstClassItem;
import com.views.apptwolistview.model.SecondClassItem;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServiceExamineManagerActivity extends BaseActivity implements SegmentView.onSegmentViewClickListener, OnItemClickListener, View.OnClickListener {

	private PullToRefreshScrollView pullToRefreshScrollView;
	private SegmentView segView;//可以隐藏中间的按钮
	private MyListView listview;
	private ServiceExmineManagerAdapter adapter;
	private List<ExmineManageInfo> exmineManageInfos = new ArrayList<>();
//	private EditText tv_search_key;
	private int state = 1;
	private int page = 1;
	private int rows = Config.ROWS;

	private static final String ASC = "asc";
	private static final String DESC = "desc";
	private String sortName, sortOrder, orderType;
	private static final String SORTNAME_TIME = "time";
	private static final String SORTNAME_COUNT = "count";
	private static final String SORTNAME_NUM = "num";
	private static String sort_qb = ""; // 1 上架时间， 2 库存数 3 销量排序

	/** 左侧一级分类的数据 */
	private List<FirstClassItem> firstList;
	/** 右侧二级分类的数据 */
	private List<SecondClassItem> secondList;

	private CommonPopupWindow commonPopupWindow;
	private int lastClick = -1;//上一次点击的group的position




	public long cId;
	private String firstCategoryId;
	private String twoCategoryId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_examine);
		MyActivityManager.getInstance().addActivity(this);
		initView();
	}

	private void initView(){
		RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
		relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
		setTvText(R.id.tv_title, "服务商品审核记录 ");
		showView(R.id.next_sure, false);
		setTvText(R.id.next_sure, "审核记录");
		textView(R.id.next_sure).setTextSize(13);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);


		firstList = new ArrayList<FirstClassItem>();




		findViewById(R.id.orderby1).setOnClickListener(selectSort);
		findViewById(R.id.orderby2).setOnClickListener(selectSort);
//		findViewById(R.id.orderby3).setOnClickListener(selectSort);
		findViewById(R.id.orderby4).setOnClickListener(this);

		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyOnRefreshListener());
		pullToRefreshScrollView.setMode(Mode.BOTH);

		listview = (MyListView)findViewById(R.id.listview);
//		listview.setOnItemClickListener(this);
		adapter = new ServiceExmineManagerAdapter(this, exmineManageInfos, new ExmineCallbackListener() {

			@Override
			public void commit(long id) {
//				loadData(id);
				startActivity(new Intent(mContext, MyEditServiceStoreActivity.class).putExtra("id", id));
			}

			@Override
			public void checkDetail(long id) {
				startActivity(new Intent(mContext, ActivityServiceProductDetails.class).putExtra("id", id));
			}
		});
		listview.setAdapter(adapter);

		segView = (SegmentView)findViewById(R.id.segView);
		segView.setOnSegmentViewClickListener(this);
		segView.setTextValues(new String[]{"待审核","审核通过", "审核拒绝"});


		// 初始化排序，按人气升序排序；
		sortName = SORTNAME_TIME;
		sortOrder = DESC;
		orderType = "2";


	}


	@Override
	protected void onResume() {
		super.onResume();
		refreshData();
	}

	private void loadData(long id) {
		showProgress("正在加载...");
		// String url = ConfigApp.HC_GET_STORE_GOODS_DETAILS;
		String url = Config.SBS_MALL_GOOD_MAIPULATION;
		RequestParams params = new RequestParams();
		params.put("id", id);
		params.put("goodType", "2");
		params.put("auditStatus","1");
		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@Override
			public void success(String response) {
				disShowProgress();

				try {
					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						return;
					}

					refreshData();
				} catch (JSONException e) {
					e.printStackTrace();
				}




			}

			@Override
			public void failed(Throwable error) {
				disShowProgress();
				showErrorMsg("网络连接失败，请稍候再试！");
			}
		});
	}


	class MyOnRefreshListener implements OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(Mode.BOTH);
			String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			page++;
			getdata();
		}
	}

	private void refreshData(){
		refreshUi();
		exmineManageInfos.clear();
		page = 1;
		getdata();
	}

	private void getdata(){

		String url = Config.SBS_MALL_LIST;
		RequestParams params = new RequestParams();
		params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid()+"");
		params.put("goodType", "2");
		params.put("orderType", orderType);
		params.put("mode", sort_qb);
		params.put("auditStatus", state);
//		params.put("type", (state+1)+"");
		params.put("categoryFirstId", StringUtils.isBlank(firstCategoryId) ? "" : firstCategoryId);
		params.put("categorySecondId", StringUtils.isBlank(twoCategoryId) ? "" : twoCategoryId);
		params.put("pageNo",page+"");
		params.put("pageSize","15");
		showProgress("加载中...");

		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@Override
			public void success(String response) {
				disShowProgress();
				try {

					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						// 刷新完成
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}
					JSONObject obj = result.getJSONObject("data");
					String mallGoodOutDTOList = obj.optString("mallGoodOutDTOList");
					if (!StringUtils.isBlank(mallGoodOutDTOList)) {

						Gson gson = new Gson();
						// json数据转换成List
						List<ExmineManageInfo> datas = gson.fromJson(mallGoodOutDTOList, new TypeToken<List<ExmineManageInfo>>() {
						}.getType());


						if (datas.size() > 0) {
							exmineManageInfos.addAll(datas);
							if (exmineManageInfos.size() > 0) {
								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}

						} else {
							if (exmineManageInfos.size() > 0) {

								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
								handler.postDelayed(new Runnable() {

									@Override
									public void run() {
										showErrorMsg("没有更多数据");
									}
								}, 1000);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}
						}
					}
					// 刷新完成
					pullToRefreshScrollView.onRefreshComplete();
					adapter.notifyDataSetChanged();



				} catch (JSONException e) {
					e.printStackTrace();
					pullToRefreshScrollView.onRefreshComplete();
				}
			}

			@Override
			public void failed(Throwable error) {
				pullToRefreshScrollView.onRefreshComplete();
				showE404();
				disShowProgress();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.orderby4:
				loadData();
				break;
			default:break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//		Intent intent = new Intent();
//		intent.setClass(mContext, ActivityProductDetails.class);
////		intent.putExtra("id", datas.get(position).getId());
//		startActivity(intent);
	}

	@Override
	public void onSegmentViewClick(int index) {
		if (index == 0){
			state = 1;
		}else if (index == 1){
			state = 2;
		}else if (index == 2){
			state = 3;
		}
//		state = index;
		firstCategoryId = "";
		twoCategoryId = "";
		sortName = SORTNAME_TIME;
		sortOrder = DESC;
		orderType = "2";
		refreshData();
	}



	private void refreshUi() {
		ImageView iv1 = imageView(R.id.iv_orderby1);
		ImageView iv2 = imageView(R.id.iv_orderby2);
//		ImageView iv3 = imageView(R.id.iv_orderby3);
		iv1.setImageResource(R.drawable.icon_arrow_nomal);
		iv2.setImageResource(R.drawable.icon_arrow_nomal);
//		iv3.setImageResource(R.mipmap.icon_arrow_nomal);
		if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
			if (SORTNAME_TIME.equals(sortName)) {
				iv1.setImageResource(ASC.equals(sortOrder) ? R.drawable.icon_arrow_up : R.drawable.icon_arrow_down);
			} else if (SORTNAME_COUNT.equals(sortName)) {
				iv2.setImageResource(ASC.equals(sortOrder) ? R.drawable.icon_arrow_up : R.drawable.icon_arrow_down);
			} else if (SORTNAME_NUM.equals(sortName)) {
//				iv3.setImageResource(ASC.equals(sortOrder) ? R.mipmap.icon_arrow_up : R.mipmap.icon_arrow_down);
			}
		}
	}

	/**
	 * 选择排序类型
	 *
	 * @param v
	 */
	public View.OnClickListener selectSort = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.orderby1:// 上架时间
					sortName = SORTNAME_TIME;
					if (sortOrder.equals(DESC)) {
						sortOrder = ASC;
						sort_qb = "1";
						orderType = "1";
					} else {
						sortOrder = DESC;
						sort_qb = "";
						orderType = "2";
					}
					break;
				case R.id.orderby2:// 库存数
					sortName = SORTNAME_COUNT;
					if (sortOrder.equals(DESC)) {
						sortOrder = ASC;
						sort_qb = "2";
						orderType = "1";
					} else {
						sortOrder = DESC;
						sort_qb = "";
						orderType = "2";
					}
					break;
				default:
					break;
			}
			refreshData();


		}
	};


	// 处理点击结果
	private void handleResult(long firstId, long secondId, String selectedName) {

		if (firstId != 0){
			firstCategoryId = firstId +"";
		}else{
			firstCategoryId = "";
		}
		if (secondId != 0) {
			twoCategoryId = secondId + "";
		}else{
			twoCategoryId = "";
		}

		if (secondId == 0) {
			this.cId = firstId;//;
		} else {
			this.cId = secondId;//;
		}
		page = 1;
		sortName = SORTNAME_TIME;
		sortOrder = DESC;
		refreshData();
	}


	private void loadData() {

		showProgress("加载中...");

		String url = Config.SBS_ENTITY_MALL_GOOD;
		RequestParams params = new RequestParams();
		params.put("goodBigtype", "1");
		params.put("groupId", MyApplication.getmInstance().getLoginMEntity().getGroupId());

		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void success(String response) {
				disShowProgress();
				try {
					List<CategoryListInfo> datas = new Gson().fromJson(response, new TypeToken<List<CategoryListInfo>>(){}.getType());
					if (datas != null && datas.size() > 0){
						setAdapterData2(datas);
					}
				} catch (Exception e) {
					e.getMessage();
				}
			}

			@Override
			public void failed(Throwable error) {
				disShowProgress();
				showE404();
			}
		});
	}



	protected void setAdapterData2(List<CategoryListInfo> list) {

		firstList.clear();

		for (int i = 0; i < list.size(); i++) {

			long firstId = list.get(i).getId();
			String firstName = list.get(i).getName();
			String url = "";// list.get(i).getCategory_icon();

			if (list.get(i).getMallCategoryList() != null && list.get(i).getMallCategoryList().size() > 0) {
				ArrayList<SecondClassItem> secondList = new ArrayList<SecondClassItem>();
				secondList.add(new SecondClassItem(0, "全部"));
				for (int j = 0; j < list.get(i).getMallCategoryList().size(); j++) {
					long secondId = list.get(i).getMallCategoryList().get(j).getId();
					String secondName = list.get(i).getMallCategoryList().get(j).getName();
					secondList.add(new SecondClassItem(secondId, secondName));
				}

				firstList.add(new FirstClassItem(firstId, firstName, url, secondList));

			} else {

				firstList.add(new FirstClassItem(firstId, firstName, url, null));
			}

		}

		final Map<String, List<SecondClassItem>> datasets = new HashMap<>();
		final String[] PListId = new String[firstList.size()];
		final String[] PList = new String[firstList.size()];
		for (int i = 0; i < PList.length; i++) {
			Log.e("city", "firstList.size():" + firstList.size());
			PList[i] = firstList.get(i).getName();
			PListId[i] = firstList.get(i).getId()+"";
			Log.e("plist", "firstList.getName:" + firstList.get(i).getName() + "=====PList[i]" + PList[i]);
			if (firstList.get(i).getSecondList() != null) {
				for (int j = 0; j < firstList.get(i).getSecondList().size(); j++) {
					datasets.put(PListId[i], firstList.get(i).getSecondList());//自相集合
					Log.e("datasets", "子项名称：" + String.valueOf(firstList.get(i).getSecondList().get(j).getName()));
					Log.e("datasets", datasets.get(PListId[i]).get(j).getName());
				}
			}else{
				datasets.put(PListId[i], null);//自相集合
			}

		}



		View view = LayoutInflater.from(this).inflate(R.layout.popup_layout2, null);

		TextView textView = view.findViewById(R.id.parent_title);
		textView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				commonPopupWindow.dismiss();
				handleResult(0, 0, null);
			}
		});

		final ExpandableListView listview = (ExpandableListView) view.findViewById(R.id.expandablelistview);


		listview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
				if (lastClick == -1) {
					listview.expandGroup(i);
				}
				if (lastClick != -1 && lastClick != i) {
					listview.collapseGroup(lastClick);
					listview.expandGroup(i);
				} else if (lastClick == i) {
					if (listview.isGroupExpanded(i)) {
						listview.collapseGroup(i);
					} else if (!listview.isGroupExpanded(i)) {
						listview.expandGroup(i);
					}
				}
				lastClick = i;

				Long parentId = Long.parseLong(PListId[i]);
				if (datasets.get(PListId[i]) == null) {
					commonPopupWindow.dismiss();
					handleResult(parentId, 0, null);
				}


				return true;
			}
		});
//        子项点击事件
		listview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView expandableListView, View view,
										int parentPos, int childPos, long l) {
				commonPopupWindow.dismiss();

				Long parentId = Long.parseLong(PListId[parentPos]);
				Long childId =  datasets.get(PListId[parentPos]).get(childPos).getId();

				handleResult(parentId, childId, null);

				return true;
			}
		});

		MyExpandableListViewAdapter adapter = new MyExpandableListViewAdapter(datasets,PListId, PList, mContext);
		listview.setAdapter(adapter);



		commonPopupWindow = new CommonPopupWindow.Builder(this)
				.setView(view)
				.setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
				.setAnimationStyle(R.style.AnimDown)
				.setBackGroundLevel(0.7f)//取值范围0.0f-1.0f 值越小越暗
				.setViewOnclickListener(new CommonPopupWindow.ViewInterface() {
					@Override
					public void getChildView(View view, int layoutResId) {

					}
				})
				.setOutsideTouchable(true)
				.create();
		commonPopupWindow.showAsDropDown(findViewById(R.id.ll_category));


	}
	
}
